var Mongoose = require('mongoose');

var knowledgeSchema = Mongoose.Schema({
    content: {
        type: String,
        default: ''
    },
    count: {
        type: Number,
        default: 1
    },
    keyword: [{
        Id: {type: Mongoose.Schema.ObjectId, ref: 'Keyword'},
        content: {type: String, default: ''}
    }],
    ideaId: {
        type: Mongoose.Schema.ObjectId,
        ref: 'Idea'
    }
}, {timestamps: true});

var Knowledge = Mongoose.model('Knowledge', knowledgeSchema);

Knowledge.createKnowledge = function (newKnowledge, callback) {
    Knowledge.findOne({content: newKnowledge.content}, function (err, oldKnowledge) {
        if (oldKnowledge) {
            oldKnowledge.count++;
            oldKnowledge.save(callback);
        } else {
            newKnowledge.save(callback);
        }
    });
};

Knowledge.getKnowledgeListByKeyword = function (keyword, callback) {
    Knowledge.aggregate([
        {$match: {keyword: {$elemMatch: {content: keyword}}}},
        {
            "$project": {
                "_id": 0,
                "content": "$content"
            }
        }
    ], callback);
};

Knowledge.autoCompleteByKnowledge = function (sentence, callback) {

    console.log("*****" + sentence)

    var sortParameter = 'createdAt',
        sortOrder = -1,
        sort = {},
        itemsperPage = 10,
        limit = parseInt(itemsperPage);
    sort[sortParameter] = sortOrder;
    var searchMatch = {content: {$regex: sentence, $options: '$i'}};
    Knowledge.aggregate([
        {$match: searchMatch},
        // {"$sort": sort},
        // {"$limit": limit},
        {
            "$project": {
                "_id": 0,
                "content": "$content"
            }
        }
    ], callback);
};

module.exports = Knowledge;